package prob1;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.stage.FileChooser;

import javax.xml.bind.JAXB;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Controller {

    @FXML
    private Button btn;

    @FXML
    private TextArea textarea;

    @FXML
    void btnpressed(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Open .txt File");
        fileChooser.setInitialDirectory(new File("./src/prob1"));
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("txt文件", "*.txt"));
        File file=fileChooser.showOpenDialog(btn.getParent().getScene().getWindow());
        List<String> container=new ArrayList<String>();
        Set<String> set = new HashSet();
        try(Scanner scanner=new Scanner(file)) {
            while (scanner.hasNext())
            {
                Pattern pattern=Pattern.compile("[a-zA-Z]+");
                Matcher matcher=pattern.matcher(scanner.next());
                while (matcher.find())
                {
                    container.add(matcher.group().toLowerCase());
                    set.add(matcher.group().toLowerCase());
                }
            }
        } catch (FileNotFoundException e) {

        }
        for (Iterator iterator= set.iterator();iterator.hasNext();)
        {
            String element = (String)iterator.next();
            textarea.appendText(String.format("%s Freq:%d\n",element,Collections.frequency(container,element)));
        }
    }
}
